package com.weixing.mall.provider.support.job;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.weixing.mall.base.enums.SysCfgCodeEnum;
import com.weixing.mall.base.wrapper.Result;
import com.weixing.mall.provider.api.model.vo.SysConfigVo;
import com.weixing.mall.provider.api.service.MemberServiceRpc;
import com.weixing.mall.provider.api.service.OrderServiceRpc;
import com.weixing.mall.provider.api.service.SysConfigServiceFeign;
import com.weixing.mall.provider.model.domain.Agent;
import com.weixing.mall.provider.service.IAgentService;
import com.weixing.mall.push.GtComponent;
import com.weixing.mall.push.PushMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * 代理商模块定时任务
 * **代理商服务基本不会做多机部署，所以定时任务可以放在这里
 * @author  Small
 * @date  2020/5/29 10:06
 * @since  1.0
 **/
@Component
public class AgentJob {


    @Autowired
    private OrderServiceRpc orderServiceRpc;
    @Autowired
    private IAgentService agentService;
    @Autowired
    private SysConfigServiceFeign sysConfigServiceFeign;
    @Autowired
    private GtComponent gtComponent;
    @Autowired
    private MemberServiceRpc memberServiceRpc;

    /**
     * 方法描述: 待审核订单推送定时任务
     * ** 每天下午5点跑定时任务
     * @Author Small
     * @param
     * @Date 2020/5/29 10:10
     * @return void
    */
    @Scheduled(cron="0 0 17 * * *")
    public void toAuditOrderTask() {
        Result<List<Long>> agentIds = orderServiceRpc.executeAuditOrderTask();

    }


    /**
     * 续费到期提醒
     *
     * @apiNote  每天凌晨5点跑定时任务
     */
    @Scheduled(cron="0 0 5 * * *")
    public void  expireTask() {
        Result<SysConfigVo> cfg = sysConfigServiceFeign.getByCode(SysCfgCodeEnum.AGENT_EXPIRE_ALERT.getCode());
        int offset =  7;
        if (cfg.isSuccess()){
          offset = cfg.getData().getCfgValue();
        }
        Date now = new Date();
        List<Agent> lists = agentService.selectEnableAll();
        if (CollUtil.isNotEmpty(lists)){
            PushMsg pushMsg = null;
            for (Agent agent : lists){
                long between = DateUtil.between(now, agent.getMaturityTime(), DateUnit.DAY,false);
                if (between >= 0 && between <= offset){
                    pushMsg = new PushMsg();
                    pushMsg.setTitle("续费通知");
                    if (0 == between){
                        between = 1;
                    }
                    pushMsg.setBody("您的代理权益还剩" +between+ "天，请尽快续费");
                    pushMsg.setClick_type("none");
                    Result<String> result = memberServiceRpc.loadAgentCid(agent.getId());
                    if (result.isSuccess()){
                        gtComponent.pushToSingleCid(pushMsg,result.getData());
                    }
                }
            }
        }

    }
}
